package com.xdclass.echo;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class EchoServer {

   
    public static void main(String[] args) {

        int port = 8765;

      //1. 创建两个线程组,一个用于处理客户端连接,一个是进行网络通信（网络读写的）
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workGroup=new NioEventLoopGroup();
        //2 创建辅助工具类ServerBootstrap，用于服务器通道的一系列配置
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workGroup)  //绑定两个线程组
                       .channel(NioServerSocketChannel.class)  //指定NIO的模式
                       .option(ChannelOption.SO_BACKLOG, 1024)	//设置tcp缓冲区
                       .option(ChannelOption.SO_SNDBUF, 32*1024)	//设置发送缓冲大小
                       .option(ChannelOption.SO_RCVBUF, 32*1024)	//这是接收缓冲大小
                       .option(ChannelOption.SO_KEEPALIVE, true)	//保持连接
                       .childHandler(new ChannelInitializer<SocketChannel>(){
                           @Override
                           protected void initChannel(SocketChannel socketChannel) throws Exception {
                               //3 在这里配置具体数据接收方法的处理
                               socketChannel.pipeline().addLast(new ServerHandler());
                           }
                       });
            
			try {
				//4 进行绑定 
				ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
				//ChannelFuture channelFuture2 = serverBootstrap.bind(8764).sync();
				//5 等待关闭
	      		channelFuture.channel().closeFuture().sync();
	      	    //channelFuture2.channel().closeFuture().sync();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally{
				bossGroup.shutdownGracefully();
	      		workGroup.shutdownGracefully();
			}
    }
}
